package com.kun.crawling.service;

import com.kun.crawling.config.DataCrawlingProperties;
import com.kun.crawling.entity.JdWareInfo;
import com.kun.crawling.mapper.JdWareInfoMapper;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author kun.li
 */
@Service
@RequiredArgsConstructor
public class DataCrawlingServiceImpl implements DataCrawlingService {

    private final DataCrawlingProperties dataCrawlingProperties;

    private final JdWareInfoMapper jdWareInfoMapper;

    @Override
    public boolean support(String type) {
        return "jd".equals(type);
    }

    @SneakyThrows
    @Override
    public void dataCrawling() {
        DataCrawlingProperties.Jd jd = dataCrawlingProperties.getJd();
        Map<String, String> cookies = new HashMap<>();
        cookies.put("thor", jd.getCookie());
        Document document = Jsoup.connect(jd.getUrl()).cookies(cookies).get();
        // 通过class获取ul标签
        Elements ul = document.getElementsByClass("gl-warp clearfix");
        // 获取ul标签下的所有li标签
        Elements liList = ul.select("li");
        for (Element element : liList) {
            String pict = element.getElementsByTag("img").first().attr("data-lazy-img");
            String price = element.getElementsByClass("p-price").first().text();
            String shopName = element.getElementsByClass("p-shop").first().text();
            JdWareInfo jdWareInfo = new JdWareInfo();
            jdWareInfo.setShopName(shopName);
            jdWareInfo.setShopPic(pict);
            jdWareInfo.setShopPrice(price);
            jdWareInfoMapper.insert(jdWareInfo);
        }
    }
}
